#include <signal.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

#define handle_error_en(en, msg) \
    do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

void *sig_thread(void *arg)
{
    sigset_t *set = (sigset_t *)arg;
    int s, sig;
    for (; ;) {
        /* 2. 调用sigwait等待信号 */
        s = sigwait(set, &sig);
        if (s != 0) {
            handle_error_en(s, "sigwait error");
        }
        printf("Signal handling thread got signal %d\n", sig);
    }
}

int main()
{
    pthread_t thread;
    sigset_t set;
    int s;

    /* 1. 在主线程中设置signal mask */
    sigemptyset(&set);
    sigaddset(&set, SIGQUIT);
    sigaddset(&set, SIGINT);
    sigaddset(&set, SIGUSR1);
    s = pthread_sigmask(SIG_BLOCK, &set, NULL);
    if (s != 0) 
        handle_error_en(s, "pthread_sigmask error");
    
    s = pthread_create(&thread, NULL, &sig_thread, (void *)&set);
    if (s != 0)
        handle_error_en(s, "pthread_create error");

    pause();
    return 0;
}

